//
//  GYActivityIndicatorView.m
//  GYCustomHUD
//
//  Created by zgy on 2025/5/26.
//

#import "GYActivityIndicatorView.h"

#define kLineCount 8
#define kAnimationDuration 1.0

@interface GYActivityIndicatorView ()
@property (nonatomic, assign) BOOL isAnimating;


@property (nonatomic, assign) CGFloat lineH;
@property (nonatomic, assign) CGFloat lineW;
@property (nonatomic, assign) CGFloat innerR;

@end

@implementation GYActivityIndicatorView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        CGFloat frameHeight = CGRectGetHeight(frame);
        CGFloat frameWidth = CGRectGetWidth(frame);
        
        CGFloat size = MIN(frameHeight, frameWidth);
        
        self.lineH = 0.5 * size / 15.0 * 6.0;
        self.innerR = 0.5 * size / 15.0 * 6.0;
        
        self.lineW = size / 16;
        if (self.lineW < 3.0) {
            self.lineW = 3.0;
        }
        
        [self setupLayers];
    }
    return self;
}

- (void)setupLayers
{
    CGPoint center = CGPointMake(self.bounds.size.width / 2.0, self.bounds.size.height / 2.0);
    for (int i = 0; i < kLineCount; i++) {
        CGFloat angle = (M_PI * 2 / kLineCount) * i;
        CGFloat xStart = center.x + _innerR * cos(angle);
        CGFloat yStart = center.y + _innerR * sin(angle);
        CGFloat xEnd = center.x + (_lineH + _innerR) * cos(angle);
        CGFloat yEnd = center.y + (_lineH + _innerR) * sin(angle);

        CAShapeLayer *line = [CAShapeLayer layer];
        line.frame = self.bounds;
        line.strokeColor = [UIColor whiteColor].CGColor;
        line.lineWidth = _lineW;
        line.lineCap = kCALineCapRound;

        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(xStart, yStart)];
        [path addLineToPoint:CGPointMake(xEnd, yEnd)];
        line.path = path.CGPath;
        line.opacity = 0.2;
        [self.layer addSublayer:line];
    }
}

- (void)startAnimating
{
    if (self.isAnimating) return;
    self.isAnimating = YES;
    for (int i = 0; i < kLineCount; i++) {
        CAShapeLayer *line = (CAShapeLayer *)[self.layer.sublayers objectAtIndex:i];
        CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"opacity"];
        anim.fromValue = @1.0;
        anim.toValue = @0.2;
        anim.duration = kAnimationDuration;
        anim.repeatCount = HUGE_VALF;
        anim.beginTime = CACurrentMediaTime() + (kAnimationDuration / kLineCount) * i;
        anim.autoreverses = NO;
        anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
        [line addAnimation:anim forKey:@"opacity"];
    }
}

- (void)stopAnimating {
    if (!self.isAnimating) return;
    self.isAnimating = NO;
    for (CAShapeLayer *line in self.layer.sublayers) {
        [line removeAllAnimations];
        line.opacity = 0.2;
    }
}

@end


